package com.sixbro.api.docs.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import static org.springdoc.core.Constants.ALL_PATTERN;

/**
 * <p>
 *  创建Swagger配置
 * </p>
 *
 * @Author: Mr.Lu
 * @Since: 2022/1/5 10:05
 */
@Configuration
public class OpenApiConfig {

    @Bean
    @Profile("!prod")
    public GroupedOpenApi actuatorApi(
            OpenApiCustomiser actuatorOpenApiCustomiser,
            OperationCustomizer actuatorCustomizer,
            WebEndpointProperties endpointProperties,
            @Value("${springdoc.version}") String appVersion
    ) {
        return GroupedOpenApi.builder()
                .group("Actuator")
                .pathsToMatch(endpointProperties.getBasePath()+ ALL_PATTERN)
                .addOpenApiCustomiser(actuatorOpenApiCustomiser)
                .addOpenApiCustomiser(openApi -> openApi.info(new Info().title("Actuator API").version(appVersion)))
                .addOperationCustomizer(actuatorCustomizer)
                .pathsToExclude("/health/*")
                .build();
    }

    @Bean
    public GroupedOpenApi usersGroup(
            @Value("${springdoc.version}") String appVersion
    ){
        return GroupedOpenApi.builder()
                .group("用户模块")
                .addOperationCustomizer((operation, handlerMethod) -> {
                    operation.addSecurityItem(new SecurityRequirement().addList("basicScheme"));
                    return operation;
                })
                .addOpenApiCustomiser(openApi -> openApi.info(new Info().title("Users API").version(appVersion)))
                .pathsToMatch("/**")
                .packagesToScan("com.sixbro.api.docs.api")
                .build();
    }

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("XXX系统API")
                        .description( "集成 springdoc-openapi 示例")
                        .termsOfService("https://springdoc.org")
                        .contact(new Contact().name("逍遥").url("http://sixbro.cn").email("luguanhua110@163.com"))
                        .license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.txt"))
                        .version("1.0")
                );
    }
}
